package com.basin.micro.admin.module.department.controller;

import cn.hutool.core.util.ObjectUtil;
import com.basin.common.core.exception.BasinException;
import com.basin.common.core.response.ResponseResult;
import com.basin.common.mp.base.BaseController;
import com.basin.micro.admin.module.department.mapper.DepartmentMapper;
import com.basin.micro.admin.module.department.pojo.entity.DepartmentEntity;
import com.basin.micro.admin.module.department.pojo.vo.DepartLevelInfoVO;
import com.basin.micro.admin.module.department.pojo.vo.DepartTreeVO;
import com.basin.micro.admin.module.department.repository.DepartmentRepository;
import com.basin.micro.admin.module.department.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.basin.micro.admin.module.department.pojo.enums.DeptLevelEnum.DEPT_LEVEL_0;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/department")
public class DepartmentController extends BaseController<DepartmentRepository, DepartmentEntity, DepartmentMapper> {

    private final DepartmentService departmentService;

    @PostMapping("/getDepartment")
    public ResponseResult<List<DepartTreeVO>> getDepartment() {
        List<DepartTreeVO> treeList = this.departmentService.getDepartmentTree();
        return ResponseResult.success(treeList);
    }

    @PostMapping("/getDepartmentLevelInfo")
    public ResponseResult<List<DepartLevelInfoVO>> getDepartmentLevelInfo() {
        List<DepartLevelInfoVO> levelList = this.departmentService.getDepartmentLevelInfo();
        return ResponseResult.success(levelList);
    }

    @Override
    public void beforeAdd(DepartmentEntity entity) {
        // 企业不需要父类 部门一定要有父级编码 且父编码的层级只能比当前部门大一级
        Integer level = entity.getDeptLevel().getLevel();
        if (level <= DEPT_LEVEL_0.getLevel()) return;
        String parentCode = entity.getParentCode();
        if (ObjectUtil.isEmpty(parentCode)) {
            throw new BasinException("部门必需有父级编码");
        }
        DepartmentEntity parentDept = departmentService.getByCode(parentCode);
        if (parentDept == null) throw new BasinException("所选父级编码：" + parentCode + " 不存在");
        if (parentDept.getDeptLevel().getLevel() + 1 != level) {
            throw new BasinException("选择数据联级关系异常");
        }
    }
}
